package com.xinghai.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinghai.common.annotation.DataScope;
import com.xinghai.common.core.domain.entity.SysDept;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.system.domain.XhCarInfo;
import com.xinghai.system.domain.XhDriverInfo;
import com.xinghai.system.mapper.XhDriverInfoMapper;
import com.xinghai.system.mapper.XhVehicleOrderInfoMapper;
import com.xinghai.system.service.ISysDeptService;
import com.xinghai.system.service.IXhCarInfoService;
import com.xinghai.system.service.IXhDriverInfoService;
import com.xinghai.system.util.XHConstant;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static com.xinghai.common.utils.SecurityUtils.getDeptId;
import static com.xinghai.common.utils.SecurityUtils.getUsername;

/**
 * 司机信息Service业务层处理
 * 
 * @author smy
 * @date 2024-07-21
 */
@Service
public class XhDriverInfoServiceImpl extends ServiceImpl<XhDriverInfoMapper, XhDriverInfo> implements IXhDriverInfoService
{
    @Autowired
    private XhDriverInfoMapper xhDriverInfoMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private IXhCarInfoService xhCarInfoService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private XhVehicleOrderInfoMapper xhVehicleOrderInfoMapper;

    /**
     * 查询司机信息
     * 
     * @param id 司机信息主键
     * @return 司机信息
     */
    @Override
    public XhDriverInfo getInfo(Long id)
    {
        return xhDriverInfoMapper.getInfo(id);
    }

    /**
     * 查询司机信息列表
     * 
     * @param xhDriverInfo 司机信息
     * @return 司机信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<XhDriverInfo> list(XhDriverInfo xhDriverInfo)
    {
        xhDriverInfo.setDelFlag("0");
        List<XhDriverInfo> list = xhDriverInfoMapper.list(xhDriverInfo);
        if (!list.isEmpty()) {
            //查询物流公司
            List<SysDept> deptList = sysDeptService.selectDeptList(new SysDept());
            list.forEach(item -> {
                Optional.ofNullable(deptList.stream().filter(f->item.getDeptId().equals(f.getDeptId())).findFirst().orElse(null)).ifPresent(val->{
                    item.setDeptName(val.getDeptName());
                });
            });
        }
        return list;
    }

    /**
     * 新增司机信息
     * 
     * @param xhDriverInfo 司机信息
     * @return 结果
     */
    @Override
    public int insert(XhDriverInfo xhDriverInfo) throws Exception {
        xhDriverInfo.setDeptId(getDeptId());
        if (this.lambdaQuery().eq(XhDriverInfo::getDeptId,xhDriverInfo.getDeptId())
                .eq(XhDriverInfo::getDelFlag, XHConstant.DEL_FLAG_NORMAL)
                .eq(XhDriverInfo::getDriverIdCard,xhDriverInfo.getDriverIdCard()).count() > 0){
            throw new Exception("当前身份证号已经存在，请勿重复录入");
        }
        xhDriverInfo.setCreateBy(getUsername());
        xhDriverInfo.setCreateTime(DateUtils.getNowDate());
        return xhDriverInfoMapper.insert(xhDriverInfo);
    }
    /**
     * 批量新增司机信息
     *
     * @param xhDriverInfoList 司机信息
     * @return 结果
     */
    @Override
    public int insertBatch(List<XhDriverInfo> xhDriverInfoList)
    {
        return xhDriverInfoMapper.insertBatch(xhDriverInfoList);
    }
    /**
     * 修改司机信息
     * 
     * @param xhDriverInfo 司机信息
     * @return 结果
     */
    @Override
    public int update(XhDriverInfo xhDriverInfo) throws Exception {
        if (this.lambdaQuery().ne(XhDriverInfo::getId,xhDriverInfo.getId())
                .eq(XhDriverInfo::getDeptId,xhDriverInfo.getDeptId())
                .eq(XhDriverInfo::getDelFlag, XHConstant.DEL_FLAG_NORMAL)
                .eq(XhDriverInfo::getDriverIdCard,xhDriverInfo.getDriverIdCard()).count() > 0){
            throw new Exception("当前身份证号已经存在，请勿重复录入");
        }
        xhDriverInfo.setUpdateTime(DateUtils.getNowDate());
        return xhDriverInfoMapper.update(xhDriverInfo);
    }

    /**
     * 批量删除司机信息
     * 
     * @param ids 需要删除的司机信息主键
     * @return 结果
     */
    @Override
    public int deleteBatch(Long[] ids) throws Exception {
        if (ids.length == 1){
            //单一删除
            this.delete(ids[0]);
        }
        int i = 0;
        for (Long id : ids) {
            //校验是否关联车辆
            if (!xhCarInfoService.getCarListByDriverId(id).isEmpty()){
                continue;
            }
            //校验是否关联订单
            if (!xhVehicleOrderInfoMapper.getOrderListByDriverId(id).isEmpty()){
                continue;
            }
            xhDriverInfoMapper.deleteBatch(ids);
            i++;
        }
        return i;
    }

    /**
     * 删除司机信息信息
     * 
     * @param id 司机信息主键
     * @return 结果
     */
    @Override
    public int delete(Long id) throws Exception {
        //校验是否关联车辆
        if (!xhCarInfoService.getCarListByDriverId(id).isEmpty()){
            throw new Exception("当前司机已被车辆关联，不允许删除");
        }
        //校验是否关联订单
        if (!xhVehicleOrderInfoMapper.getOrderListByDriverId(id).isEmpty()){
            throw new Exception("当前司机已产生订单，不允许删除");
        }
        return xhDriverInfoMapper.delete(id);
    }

    /**
     * 导入司机信息信息
     *
     * @param list 司机信息信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<XhDriverInfo> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            XhDriverInfoMapper xhDriverInfoMapper = sqlSession.getMapper(XhDriverInfoMapper.class);
            list.forEach(item -> {
                item.setDeptId(getDeptId());
                if (this.lambdaQuery()
                        .eq(XhDriverInfo::getDelFlag,XHConstant.DEL_FLAG_NORMAL)
                        .eq(XhDriverInfo::getDriverIdCard,item.getDriverIdCard())
                        .eq(XhDriverInfo::getDeptId,item.getDeptId()).count() == 0) {
                    xhDriverInfoMapper.insert(item);
                }
            });
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    /**
     * 接单页面-根据车辆ID查询司机列表
     */
    @Override
    public List<XhDriverInfo> getDriverListByCar(XhCarInfo xhCarInfo) {
        if (xhCarInfo.getId() == null) {
            return Collections.emptyList();
        }
        //查询车辆信息
        XhCarInfo xhCarInfoDB = xhCarInfoService.getById(xhCarInfo.getId());
        if (xhCarInfoDB == null || StringUtils.isNull(xhCarInfoDB.getDriverId())){
            return Collections.emptyList();
        }
        //查询司机信息
        return this.lambdaQuery().in(XhDriverInfo::getId, Arrays.asList(xhCarInfoDB.getDriverId().split(",")))
                .orderByDesc(XhDriverInfo::getCreateTime).list();
    }

    @Override
    @DataScope(deptAlias = "c")
    public List<XhDriverInfo> carDriverList(XhDriverInfo xhDriverInfo) {
        return xhDriverInfoMapper.carDriverList(xhDriverInfo);
    }
}
